<template>
    <div>
        <div style="margin-bottom: 10px">
            <i-button type="primary" style="margin-right: 10px" @click="server_ip_init">初始化</i-button>
            <i-button type="error" style="margin-right: 10px" @click="batch_update">批量更新</i-button>
            <i-button type="error" style="margin-right: 10px" @click="btn_export">导出数据</i-button>
        </div>
        <!-- 540小屏幕 -->
        <i-table border stripe  :columns="format" :data="show_list" :height="sharedState.tableHeight" >
            <template slot-scope="{ row, index }" slot="action">
                <Button type="primary" style="margin-bottom: 5px "  @click="btn_ssh_connect(index)">ssh</Button>
            </template>
        </i-table >
        <div style="text-align: center;margin-top: 10px;">
            <Page ref="page" :total="total" :page-size="pageSize"  @on-change="changePage" show-total/>
        </div>
        <!-- 服务器初始化模态框 -->
        <Modal v-model="show_server_init_modal" width="600">
            <p slot="header" style="color:#f60;text-align:center;">
                <span>服务器IP列表初始化</span>
            </p>
            <div style="">
                <Form ref="server_init" :model="server_init" :rules="server_init_rules"  label-position="left" :label-width="100">
                    <Form-Item label="IP:"  prop="ip">
                        <Input v-model="server_init.ip"  placeholder="192.168.11.2(IP段内任一地址)" />
                    </Form-Item> 
                    <Form-Item label="掩码:"  prop="mask">
                        <Input v-model="server_init.mask" placeholder="24"  />
                    </Form-Item> 
                    <Form-Item label="检测端口:"  prop="port">
                        <Input v-model="server_init.port" placeholder="22"  />
                    </Form-Item> 
                </Form> 
            </div>
            <div slot="footer">
                <Button type="primary" size="large"  @click="btn_server_init('server_init')">提交</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
import axios from 'axios';
import { server_list,
batch_update_server,
server_host_init,
export_cmdb
// server_user_info 
} from  '@/api'
import store from '@/store'
import { post } from '@/api/http'
import { get_placement,show_simple_page } from '@/common/util'


export default {
    data() {
        return {
            sharedState: store.state,
            format: [
                {
                    title: '名字',key: 'hostname'
                },
                {
                    title: '状态',key: 'status',
                    align: 'center',
                    render:(h,params) => {
                        if(params.row.status=='在线'){
                            return h('span',{
                                style: {
                                    color: '#19be6b',
                                }
                            },params.row.status)
                        }else if (params.row.status=='忙碌'){
                            return h('span',{
                                style: {
                                    color: '#ff9900'
                                }
                            },params.row.status)
                        }else if (params.row.status=='关机'){
                            return h('span',{
                                style: {
                                    color: '#ed4014'
                                }
                            },params.row.status)
                        }else {
                            return h('span',{},params.row.status)
                        }
                    }
                },
                {
                    title: '私有IP',key: 'private_ip',
                },
                {
                    title: '公有IP',key: 'public_ip',
                    render: (h,params) =>{
                        let public_ip = params.row.public_ip
                        if(!public_ip){
                            return h('p','无')
                        }else{
                            return h('p',public_ip)
                        }
                    }
                },
                {
                    title: '云类别',key: 'cloud',
                    render: (h,params) =>{
                        let cloud = params.row.cloud
                        if(!cloud){
                            return h('p','无')
                        }else{
                            return h('p',cloud)
                        }
                    }
                },
                {
                    title: '系统',key: 'system_info',width:100,
                    render: (h, params) => {
                        return h('div', [
                            h('pre', params.row.system_info.system_version)
                        ]);
                    }
                },
                {
                    title: 'CPU',align:'center',
	
                    children:[
                        {
                            title: '核数/线程数',align:'center',
                            render: (h,params) => {
                                let cpu = params.row.cpu
                                let cpu_core = cpu.cpu_core
                                let cpu_thread = cpu.cpu_thread
                                let value = cpu_core+"/"+cpu_thread
                                return h('p',value)
                            }
                        },
                        {
                            title: '使用比例',align:'left',
                            render: (h, params) => {
                                let cpu = params.row.cpu
                                let cpu_thread = cpu.cpu_thread
                                let load = params.row.cpu_load
                                let one_minute_load = load['1min']

                                let value = (one_minute_load/cpu_thread*100).toFixed(1)

                                return h('p',value+'%')
                            }
                        },
                    ]
                },
                {
                    title: '内存(M)',align:'center',

                    children:[
                        {
                            title: '使用/总量',align:'center',
                            render: (h,params) => {
                                let memory = params.row.memory
                                let memory_total= (memory.memory_total/1024).toFixed(1)
                                let memory_used  = (memory.memory_used/1024).toFixed(1)
                                let value = memory_used+"G/"+memory_total+"G"
                                return h('p',value)
                            }
                        },
                        {
                            title: '使用比例',align:'left',
                            render: (h, params) => {
                                let memory = params.row.memory
                                let memory_total= memory.memory_total
                                let memory_used  = memory.memory_used
                                let value = parseFloat((memory_used/memory_total*100).toFixed(1))
                                if (value > 50 && value < 75){
                                    return  h('i-progress',{ props:{percent: value,'stroke-width': 15,'status':'active'}}, value+'%');
                                } else if (value >= 75){
                                    return  h('i-progress',{ props:{percent: value,'stroke-width': 15,'status':'wrong'}}, value+'%');
                                } else {
                                    return  h('i-progress',{ props:{percent: value,'stroke-width': 15,'status':'success'}}, value+'%');
                                }
                            }
                        },
                    ]
                },
                {
                    title: '磁盘',align:'center',
                    children:[
                        {
                            title: '使用/总量',align:'center',
                            render: (h,params) => {
                                let disk_info = params.row.disk_info
                                let disk_total= disk_info.disk_total.toFixed(0)
                                let disk_used  = disk_info.disk_used.toFixed(0)
                                let value = disk_used+"G/"+disk_total+"G"
                                return h('p',value)
                            }
                        },
                        {
                            title: '使用比例',align:'left',
                            render: (h, params) => {
                                let disk_info = params.row.disk_info
                                let disk_total= disk_info.disk_total
                                let disk_used  = disk_info.disk_used
                                let value = parseFloat((disk_used/disk_total*100).toFixed(1))
                                if (value > 50 && value < 75){
                                    return  h('i-progress',{ props:{percent: value,'stroke-width': 15,'status':'active'}}, value+'%');
                                } else if (value >= 75){
                                    return  h('i-progress',{ props:{percent: value,'stroke-width': 15,'status':'wrong'}}, value+'%');
                                } else {
                                    return  h('i-progress',{ props:{percent: value,'stroke-width': 15,'status':'success'}}, value+'%');
                                }
                            }
                        },
                    ]

                },
                {
                    title: '块设备(G)',key: 'device_info',
                    render : (h,params) => {
                        let device_info = params.row.device_info 
                        if (device_info.length == 0 || device_info == null ){
                            return   h('p','无')
                        }else{
                            let value = JSON.stringify(device_info,undefined,4)
                            let placement = get_placement(params)
                            return h('Poptip', {props:{'trigger':'hover','word-wrap':true,'placement':placement,content:value}},[
                                h('a', '显示')
                            ]);
                        }
                    }
                },   

                {
                    title: '磁盘挂载(G)',key: 'disk_mount_list',
                    render : (h,params) => {
                        let disk_mount_list = params.row.disk_mount_list 
                        if (disk_mount_list.length == 0 || disk_mount_list == null ){
                            return   h('p','无')
                        }else{
                            let value = JSON.stringify(disk_mount_list,undefined,4)
                            let placement = get_placement(params)
                            return h('Poptip', {props:{'trigger':'hover','word-wrap':true,'placement':placement,content:value}},[
                                    h('a', '显示')
                            ]);
                        }
                    }
                },

                {
                    title: '更新时间',key: 'update_time'
                },
                {
                    title: '操作',slot: 'action',width: 100,align: 'center'
                }
            ],
            // 服务器初始化
            show_server_init_modal:false,
            server_init:{
                ip: '192.168.11.22',
                mask: '24',
                port: 52000,
            },
            server_init_rules:{
                ip: [
                    {required: true,message:'请输入IP',trigger: 'blur'},
                ],
                mask: [
                    {required: true,message:'请输入掩码20-32',trigger: 'blur'},
                ],
            },

            total_list: [],
            show_list: [],
            // 分页
            total: 0,
            pageSize: 10,
        }
    },
    methods: {
        btn_export(){
            axios({
                method:'post',
                url: export_cmdb,
                responseType: 'blob'
            }).then((res) => {
                const link = document.createElement('a')
                // console.log(res)
                // let cd = res.headers;
                // console.log(cd)
                let blob = new Blob([res.data], {type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})
                link.style.display = 'none'
                link.href = URL.createObjectURL(blob)
                // link.download = res.headers['content-disposition'] //下载后文件名
                link.download = 'server.xlsx' //下载的文件名
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
            }).catch(error => {
                console.log(error)
            })

        },
        async btn_ssh_connect(index){
            let status = this.show_list[index].status
            if(status == '关机' ){
                this.$Message.error('非在线主机不能连接')
                return
            }
            let ip = this.show_list[index].private_ip

            // this.$router.push({name: 'webssh',query: {hostname: ip} })

            // window.open(record_url+"?id="+id,"_blank");
            const { href } = this.$router.resolve({
                name: 'webssh'
            });
            window.open(href+"?hostname="+ip, '_blank');
            

        },
        checkIP(ip)  {  
            let exp=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;  
            let reg = ip.match(exp);  
            if(reg==null)  {  
                return false
            }  
            else  {  
                return true
            }  
        },

        // 提交初始化事件
        btn_server_init(name){
            let validate = false
            this.$refs[name].validate((valid) => {
                if (valid) {
                    // this.$Message.success('表单数据验证成功!');
                    validate = true
                    console.log('表单数据验证成功!')
                } else {
                    this.$Message.error('表单数据验证失败!');
                    validate = false
                }
            })
            if(!validate) return
            let ip = this.server_init.ip
            let mask = parseInt(this.server_init.mask)
            let port = parseInt(this.server_init.port)
            if(!this.checkIP(ip)){
                this.Message.error("IP地址不合法")
                return 
            }
            if(mask>32 || mask < 20){
                this.$Message.error("掩码必须大于等于20并且小于等于32")
                return
            }
            if(port < 0 || port> 65535){
                this.$Message.error("端口必须大于0并且小于65536")
                return   
            }

            let url = server_host_init
            let method = 'post'
            let data = {"ip":ip,"mask":mask,"port":port}
            axios({
                url:url,data:data,method:method,
            }).then( (response) => {
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success("服务器IP列表已在后台初始化，请稍后查看初始化日志")
                    this.show_server_init_modal = false
                }else {
                    this.$Message.error('服务器IP列表初始化失败')
                }
            })
        },
        // 批量服务器初始化，入库
        server_ip_init(){
            this.show_server_init_modal = true
        },
        // 批量服务器更新信息
        batch_update(){
            let url = batch_update_server
            let method = 'post'
            axios({
                url:url,method:method,timeout:60000
            }).then( (response) => {
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('批量更新进行中，稍后请查看更新日志')
                    this.refresh()
                }else {
                    this.$Message.error('批量更新失败，稍后请查看更新日志')
                }
            })
        },
        changePage(index) {
            let _start = (index -1) * this.pageSize
            let _end = index * this.pageSize
            this.show_list = this.total_list.slice(_start,_end)
        },
        refresh() {
            post(server_list).then( (response) => {
                show_simple_page(this,response)
            })

        }
    },
    mounted: function() {
        setTimeout(() =>{
            this.refresh();
        },200); 
    }
}
</script>
<style>
    pre{
        white-space: pre-wrap!important;
        word-wrap: break-word!important;
        *white-space:normal!important;
    }
</style>